package club.yuit.rmq.service;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.apis.ClientConfiguration;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.StaticSessionCredentialsProvider;
import org.apache.rocketmq.client.apis.message.Message;
import org.apache.rocketmq.client.apis.message.MessageBuilder;
import org.apache.rocketmq.client.apis.producer.Producer;

import java.util.Map;

/**
 * @author: yuit
 * @date: 2023/12/01 17:31
 */
public class ProducerService {

    private ClientServiceProvider provider;


    public ProducerService() {
        provider = ClientServiceProvider.loadService();
    }

    public Producer normalProducer(){
        try {
           return provider.newProducerBuilder()
                    .setTopics()
                    .setClientConfiguration(configuration())
                    .build();
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
    }


    public Message createMessage(String v,String topic){
        return provider.newMessageBuilder()
                .setBody(v.getBytes())
                .setTopic(topic)
                .build();
    }

    public Message createMessage(String body, String topic, String tag, String keys, String messageGroup,
                                 Long deliveryTime,Map<String,String> properties){
        MessageBuilder messageBuilder = provider.newMessageBuilder()
                .setBody(body.getBytes())
                .setTopic(topic);

        if (StringUtils.isNoneEmpty(tag)) {
            messageBuilder.setTag(tag);
        }

        if (StringUtils.isNoneEmpty(messageGroup)) {
            messageBuilder.setMessageGroup(messageGroup);
        }

        if (deliveryTime!= null) {
            messageBuilder.setDeliveryTimestamp(deliveryTime);
        }

        if (StringUtils.isNoneEmpty(keys)) {
            messageBuilder.setKeys(keys);
        }

        if (properties!= null &&!properties.isEmpty()) {
           properties.forEach(messageBuilder::addProperty);
        }



        return messageBuilder.build();

    }





    private ClientConfiguration configuration(){
        String endpoints = System.getProperty("endpoints");
        String accessKey = System.getProperty("accessKey");
        String secretKey = System.getProperty("secretKey");
        return   ClientConfiguration.newBuilder()
                .setCredentialProvider(
                        new StaticSessionCredentialsProvider(
                                accessKey,secretKey
                        )
                )
                .setEndpoints(endpoints)
                .build();
    }

}
